<template>
  <div class="editable-element-chart" :class="{ 'lock': elementInfo.lock }" :style="{
    top: elementInfo.top + 'px',
    left: elementInfo.left + 'px',
    width: elementInfo.width + 'px',
    height: elementInfo.height + 'px'
  }">
    <div class="rotate-wrapper" :style="{ transform: `rotate(${elementInfo.rotate}deg)` }">
      <!-- dblclick事件：在单个元素上单击两次鼠标的指针设备按钮（通常是小鼠的主按钮）时触发。 -->
      <div class="element-content" :style="{
        backgroundColor: elementInfo.fill
      }" v-contextmenu="contextmenu" @mousedown="$event => handleSelectElement($event)"
        @dblclick="() => openDataEditor()">
        <ElementOutline :width="elementInfo.width" :height="elementInfo.height" :outline="elementInfo.outline" />
        <Chart :width="elementInfo.width" :height="elementInfo.height" :type="elementInfo.chartType"
          :data="elementInfo.data" :options="elementInfo.options" :themeColor="elementInfo.themeColor"
          :gridColor="elementInfo.gridColor" :legends="elementInfo.data.legends" :legend="elementInfo.legend || ''" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineProps, PropType } from 'vue'
import { PPTChartElement } from '@/types/slides'
import { ContextmenuItem } from '@/components/Contextmenu/types'
import emitter, { EmitterEvents } from '@/utils/emitter'

import ElementOutline from '../ElementOutline.vue'
import Chart from './Chart.vue'

const props = defineProps({
  elementInfo: {
    type: Object as PropType<PPTChartElement>,
    required: true
  },
  selectElement: {
    type: Function as PropType<(e: MouseEvent, element: PPTChartElement, canMove?: boolean) => void>,
    required: true
  },
  contextmenu: {
    type: Function as PropType<() => ContextmenuItem[] | null>
  }
})

const handleSelectElement = (e: MouseEvent) => {
  if (props.elementInfo.lock) return
  e.stopPropagation()
  props.selectElement(e, props.elementInfo)
}

const openDataEditor = () => {
  // 实现两个组件之间的通信，Vue3中没有EventBus，故使用mitt.js代替，原理还是EventBus
  emitter.emit(EmitterEvents.OPEN_CHART_DATA_EDITOR)
}
</script>

<style lang="scss" scoped>
.editable-element-chart {
  position: absolute;

  &.lock .element-content {
    cursor: default;
  }
}

.rotate-wrapper {
  width: 100%;
  height: 100%;
}

.element-content {
  width: 100%;
  height: 100%;
  overflow: hidden;
  cursor: move;
}
</style>